package com.test.mooan.labama.activity_fragment_boom.process_boom;

import static com.test.mooan.labama.constants_boom.Constant_boom.Start_Camera;
import static com.test.mooan.labama.utils_boom.Permissionutil_boom.Permission_Code_Camera;
import static com.test.mooan.labama.utils_boom.imageUtil_boom.ImageConvert_boom.getImageFilePath;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.PickVisualMediaRequest;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.test.mooan.labama.R;
import com.test.mooan.labama.activity_fragment_boom.base_boom.BaseApplication_boom;
import com.test.mooan.labama.activity_fragment_boom.base_boom.BaseInfoActivity_boom;
import com.test.mooan.labama.bean_boom.config_info_boom.UrlInfo_boom;
import com.test.mooan.labama.dialog_boom.PhotoChooseDialog_boom;
import com.test.mooan.labama.utils_boom.Permissionutil_boom;
import com.test.mooan.labama.utils_boom.Threadutils_boom;
import com.test.mooan.labama.utils_boom.helper_boom.UserInfoHelper_boom;
import com.test.mooan.labama.utils_boom.http_boom.HttpManager_boom;
import com.test.mooan.labama.utils_boom.imageUtil_boom.ImageConvert_boom;
import com.test.mooan.labama.view_boom.widget_boom.SelectView_boom;
import com.test.mooan.labama.view_boom.widget_boom.TitleView_boom;

import java.io.File;
import java.util.TreeMap;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class OcrUpldActivity_boom extends BaseInfoActivity_boom {

    private ImageButton ocrImage1Ib, ocrImage2Ib;

    private String image1Url, image2Url;
    private Bitmap image1Bitmap, image2Bitmap;

    private boolean isImageReverse = false;

    private SelectView_boom cardTypeSv;
    private View img2Layout;
    private TextView img1Tv,img2Tv;

    private CheckBox deleteDataCb;

    private static String CT_IdCard="National ID card",CT_Passport="Passport",CT_DrvingLicense="Driving license",CT_Election = "Election card";
    private static final String WD_IdCard="IDCARD",WD_Passport="PASSPORT",WD_DrvingLicense="DRIVING";

    private String selectType = CT_IdCard;

    private Runnable startCameraRunnable;

    private String imgPath = "";

    private ActivityResultLauncher<PickVisualMediaRequest> pickMedia;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ocr_upld_boom);

        pickMedia = registerForActivityResult(new ActivityResultContracts.PickVisualMedia(),uri -> {
            if (uri != null){
                photoUri_boom = uri;
                imgPath = ImageConvert_boom.getBitmapFilePathFromURI(this,photoUri_boom);
                onPhotoGet();
            }
        });

        init();
    }

    private void init(){
        TitleView_boom titleView = findViewById(R.id.activity_ocr_upload_view_title);
        setBackBtn_boom(titleView.getBackIb());

        ocrImage1Ib = findViewById(R.id.activity_ocr_upload_ib_ocr_image_1);
        ocrImage2Ib = findViewById(R.id.activity_ocr_upload_ib_ocr_image_2);

        cardTypeSv = findViewById(R.id.activity_ocr_upload_sv_cardtype);
        img1Tv = findViewById(R.id.activity_ocr_upload_tv_img1);
        img2Tv = findViewById(R.id.activity_ocr_upload_tv_img2);

        deleteDataCb = findViewById(R.id.activity_ocr_upload_cb_delete_data);

        img2Layout = findViewById(R.id.activity_ocr_upload_layout_ocr_image_2);

        ocrImage1Ib.setOnClickListener(v -> {

            UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_IMAGE_1_CLICK").toUpperCase());

            new PhotoChooseDialog_boom(
                    this,
                    () -> {//打开相机
                        isImageReverse = false;
                        startCamera();
                    },
                    () -> {//相册选择
                        isImageReverse = false;
                        openAlbum();
                    }
                    ).show();

        });

        ocrImage2Ib.setOnClickListener(v -> {
            UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_IMAGE_2_CLICK").toUpperCase());

            new PhotoChooseDialog_boom(
                    this,
                    () -> {//打开相机
                        isImageReverse = true;
                        startCamera();
                    },
                    () -> {//相册选择
                        isImageReverse = true;
                        openAlbum();
                    }
            ).show();

        });

        findViewById(R.id.activity_ocr_upload_btn_submit).setOnClickListener(v -> {

            UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_SAVE_CLICK").toUpperCase());

            HttpManager_boom.getInstance().saveUserPointForBatch();

            if (TextUtils.isEmpty(image1Url)||(TextUtils.isEmpty(image2Url)&&!selectType.equalsIgnoreCase(CT_Passport))){
                showToast_boom(getString(R.string.upload_ocr_tip));
                return;
            }

            HttpManager_boom.getInstance().uploadInfo(UrlInfo_boom.gInstance().gCyk3(), new TreeMap<String,String>(){{
                put("cardImgUrl", image1Url);
                put("cardBackImgUrl", selectType.equalsIgnoreCase(CT_Passport) ? "":image2Url);
                put("cardType",getTypeWd());
                put("deleteDataFlag", deleteDataCb.isChecked() ? "YES" : "NO");
            }});
        });

        CT_IdCard = getString(R.string.ocr_type_id_card);
        CT_Passport = getString(R.string.ocr_type_passport);
        CT_DrvingLicense = getString(R.string.ocr_type_driving_license);
        CT_Election = getString(R.string.ocr_type_election_card);

        cardTypeSv.addListItem(CT_IdCard,CT_Passport,CT_DrvingLicense,CT_Election);

        cardTypeSv.setOnPickListener(pickStr -> {
            if (CT_IdCard.equalsIgnoreCase(pickStr)){
                initTypeIdCard();
            }else if (CT_Passport.equalsIgnoreCase(pickStr)){
                initTypePassport();
            }else if (CT_DrvingLicense.equalsIgnoreCase(pickStr)){
                initTypeDrvingLicense();
            }else if (CT_Election.equalsIgnoreCase(pickStr)){
                initTypeElectionCard();
            }

        });

        cardTypeSv.setInput(CT_IdCard);
        initTypeIdCard();
    }

    private void startCamera(){
        runWithCameraPermission(() -> {
            Intent intent = new Intent();
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);

            String imageFilePath = getImageFilePath();
            File imageFile = new File(imageFilePath);
            imgPath = imageFilePath;
            String providerAuthority = BaseApplication_boom.getInstant_boom().getPackageName() + ".file_provider";
            photoUri_boom = FileProvider.getUriForFile(BaseApplication_boom.getInstant_boom(), providerAuthority, imageFile);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri_boom);
            startActivityForResult(intent, Start_Camera);
        });
    }

    private void openAlbum(){

        pickMedia.launch(
                new PickVisualMediaRequest.Builder()
                        .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE)
                        .build()
        );

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Start_Camera) {
            onPhotoGet();
        }
    }

    private void onPhotoGet() {

        if (photoUri_boom == null) {
            if (isImageReverse) image2Url = null;
            else image1Url = null;
            showToast_boom(getString(R.string.photo_upload_again_tip));
            return;
        }

        if (!TextUtils.isEmpty(imgPath)) {
            ImageConvert_boom.startConvertImage(
                    new File(imgPath),
                    (localPath, thumpImg) -> {
                        if (isImageReverse) image2Bitmap = thumpImg;
                        else image1Bitmap = thumpImg;
                        Threadutils_boom.getInstance().runOnChildThread(
                                () -> HttpManager_boom.getInstance().uploadImage(localPath)
                        );
                    }
            );
        } else {
            if (isImageReverse) image2Url = null;
            else image1Url = null;
            showToast_boom(getString(R.string.photo_upload_again_tip));
        }
    }

    public void onPhotoUploadResponse(String imageUrl){
        if (TextUtils.isEmpty(imageUrl)||(!isImageReverse&& image1Bitmap ==null)||(isImageReverse&& image2Bitmap ==null)){
            showToast_boom(getString(R.string.photo_upload_again_tip));
            return;
        }

        if (isImageReverse){
            this.image2Url = imageUrl;
            ocrImage2Ib.setBackground(null);
            ocrImage2Ib.setImageBitmap(image2Bitmap);
        }else {
            this.image1Url = imageUrl;
            ocrImage1Ib.setBackground(null);
            ocrImage1Ib.setImageBitmap(image1Bitmap);
        }
    }

    @SuppressLint("SetTextI18n")
    private void initTypeIdCard(){

        clearImg();

        selectType = CT_IdCard;
        img1Tv.setText(getString(R.string.ocr_idcard_1));
        img2Tv.setText(getString(R.string.ocr_idcard_2));
        img2Layout.setVisibility(View.VISIBLE);
    }

    @SuppressLint("SetTextI18n")
    private void initTypePassport(){

        clearImg();

        selectType = CT_Passport;
        img1Tv.setText(getString(R.string.ocr_passport));
        img2Layout.setVisibility(View.GONE);

    }

    @SuppressLint("SetTextI18n")
    private void initTypeDrvingLicense(){

        clearImg();

        selectType = CT_DrvingLicense;
        img1Tv.setText(getString(R.string.ocr_drving_license_1));
        img2Tv.setText(getString(R.string.ocr_drving_license_2));
        img2Layout.setVisibility(View.VISIBLE);

    }
    @SuppressLint("SetTextI18n")
    private void initTypeElectionCard(){

        clearImg();

        selectType = CT_Election;
        img1Tv.setText(getString(R.string.ocr_election_card_1));
        img2Tv.setText(getString(R.string.ocr_election_card_2));
        img2Layout.setVisibility(View.VISIBLE);
    }

    private void clearImg(){
        image1Url = "";
        image2Url = "";
        image1Bitmap = null;
        image2Bitmap = null;

        ocrImage1Ib.setBackgroundColor(Color.TRANSPARENT);
        ocrImage1Ib.setImageResource(R.drawable.img_ocr);

        ocrImage2Ib.setBackgroundColor(Color.TRANSPARENT);
        ocrImage2Ib.setImageResource(R.drawable.img_ocr_reverse);
    }

    private String getTypeWd(){

        if (CT_IdCard.equalsIgnoreCase(selectType)){
            return WD_IdCard;
        }else if (CT_Passport.equalsIgnoreCase(selectType)){
            return WD_Passport;
        }else if (CT_DrvingLicense.equalsIgnoreCase(selectType)){
            return WD_DrvingLicense;
        }else if (CT_Election.equalsIgnoreCase(selectType)){
            return WD_IdCard;
        }

        return "";
    }

}